package com.jic.order.controller.rest;

import com.alibaba.fastjson.JSONArray;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.redis.RedisClientTemplate;
import com.jic.member.api.rest.MemberInformationApi;
import com.jic.member.request.MeinformationRequest;
import com.jic.order.constant.OrderAfterSalesConstant;
import com.jic.order.entity.OrderAfterSaleApplyModel;
import com.jic.order.entity.OrderAfterSaleFlowRecordModel;
import com.jic.order.entity.OrderBaleDelivery;
import com.jic.order.entity.OrderGoods;
import com.jic.order.entity.OrderLogisticsCompany;
import com.jic.order.enums.AfterSaleOperateTypeEnum;
import com.jic.order.enums.AfterSaleStatusEnum;
import com.jic.order.enums.OrderEnum;
import com.jic.order.request.OrderAfterSaleApplyAddRequest;
import com.jic.order.request.OrderAfterSaleApplyCancelRequest;
import com.jic.order.request.OrderAfterSaleApplyQueryPageListRequest;
import com.jic.order.request.OrderAfterSaleApplyQueryRequest;
import com.jic.order.request.OrderAfterSaleCountRequest;
import com.jic.order.response.OrderAfterSaleApplyQueryResponse;
import com.jic.order.response.OrderInfo;
import com.jic.order.rest.response.OrderLogisticsCompanyRestResponse;
import com.jic.order.service.OrderAfterSaleApplyService;
import com.jic.order.service.OrderAfterSaleFlowRecordService;
import com.jic.order.service.OrderBaleDeliveryService;
import com.jic.order.service.OrderGoodsService;
import com.jic.order.service.OrderLogisticsCompanyService;
import com.jic.order.service.OrderService;
import com.jic.order.utils.BeanUtil;
import com.jic.order.utils.SerialNoUtil;
import com.jic.product.after.api.ProductListApi;
import com.jic.product.after.response.ProductAfterInfoByIdResponse;
import com.jic.product.store.request.MStoreFrozenRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@Api(tags = "API-售后")
@RequestMapping(value = "afterSale")
@RestController
public class AfterSaleRest {

    private final static Logger logger = LoggerFactory.getLogger(AfterSaleRest.class);

    @Autowired
    RedisClientTemplate redisClientTemplate;
    @Autowired
    OrderAfterSaleFlowRecordService orderAfterSaleFlowRecordService;
    @Autowired
    OrderLogisticsCompanyService orderLogisticsCompanyService;
    @Autowired
    OrderBaleDeliveryService orderBaleDeliveryService;
    @Resource
    ProductListApi productListApi;
    @Resource
    MemberInformationApi memberInformationApi;
    @Autowired
    private OrderAfterSaleApplyService modelService;
    @Autowired
    private OrderGoodsService orderGoodsService;
    @Autowired
    private OrderService orderService;

    @ApiOperation(value = "售后-售后申请")
    @RequestMapping(value = "/apply", method = {RequestMethod.POST})
    @ResponseBody
    public RestResult<Boolean> orderAfterSaleApplyAdd(@RequestBody OrderAfterSaleApplyAddRequest req) {
        logger.info("-------进入售后申请------{}", req);
        if (StringUtils.isEmpty(req.getOrderNo())) {
            return RestResult.error("4000", "请传订单编号");
        }

        // 获取用户id
        String userStr = redisClientTemplate.get("H5_LOGIN_TOKEN_" + req.getToken());
        if (StringUtils.isEmpty(userStr)) {
            return RestResult.error("4000", "非法请求");
        }
        Map<String, Object> userMap = JSONArray.parseObject(userStr, HashMap.class);
        Long userId = Long.valueOf(userMap.get("id").toString());
        String mobile = userMap.get("phone") == null ? null : userMap.get("phone").toString();
        String username = userMap.get("name") == null ? userMap.get("nickName").toString() : userMap.get("name").toString();
        try {
            Date currentDate = new Date();
            OrderAfterSaleApplyModel model = new OrderAfterSaleApplyModel();
            BeanUtils.copyProperties(req, model);
            model.setMemberId(userId);
            model.setApplyPhone(mobile);
            model.setStatus(model.getAfterSaleType() == 4 ? AfterSaleStatusEnum.EXCHANGE_PENDING.getCode() : AfterSaleStatusEnum.APP_REFUND.getCode());
            model.setApplyName(username);
            model.setApplyTime(currentDate);
            model.setCreateName(username);
            model.setCreateTime(currentDate);
            model.setCreator(userId);
            model.setUpdateName(username);
            model.setUpdateTime(currentDate);
            model.setUpdater(userId);

            // 获取订单信息
            RestResult<OrderInfo> orderInfoRR = orderService.info(req.getOrderNo());
            if (null != orderInfoRR && OrderEnum.SUCCESS.getCode().equals(orderInfoRR.getCode())) {
                OrderInfo orderInfo = orderInfoRR.getData();
                model.setMerchantId(orderInfo.getMerchantId());
                model.setStoreId(orderInfo.getStoreId());
                model.setOrderTime(orderInfo.getBuyTime());
            } else {
                logger.info("------无订单信息,订单编号为:{},用户id 为:{}--", req.getOrderNo(), userId);
                return RestResult.error(OrderEnum.NO_ORDER_INFO.getCode(), OrderEnum.NO_ORDER_INFO.getMessage());
            }

            // 设置售后编码
            model.setAfterSaleNo(SerialNoUtil.genAfterSaleNo());

            // 查询订单商品信息
            OrderGoods goodsCondition = new OrderGoods();
            goodsCondition.setGoodsId(req.getGoodsId());
            goodsCondition.setOrderNo(req.getOrderNo());
            List<OrderGoods> orderGoodsList = orderGoodsService.query(goodsCondition);
            if (null != orderGoodsList && orderGoodsList.size() > 0) {
                OrderGoods orderGoods = orderGoodsList.get(0);
                model.setGoodsId(orderGoods.getGoodsId());
                model.setGoodsImgUrl(orderGoods.getGoodsImgUrl());
                model.setGoodsName(orderGoods.getGoodsName());
                model.setGoodsNum(orderGoods.getGoodsNum());
                model.setGoodsPrice(orderGoods.getSaleUnitPrice());
                model.setGoodsRealPrice(orderGoods.getActualPayTotalAmount());
                // 实际退款金额
                model.setReturnRealAmount(orderGoods.getActualPayTotalAmount());

                // 库存滚回
//                MStoreFrozenRequest mStoreFrozenRequest = new MStoreFrozenRequest();
//                mStoreFrozenRequest.setApplyNum(Long.valueOf(orderGoods.getGoodsNum()));
//                mStoreFrozenRequest.setCode(orderGoods.getOrderNo());
//                mStoreFrozenRequest.setProductId(orderGoods.getGoodsId());
//                mStoreFrozenRequest.setFrozenFlag(false);
//                productListApi.frozenStock(mStoreFrozenRequest);

                // 退款售后-提交申请消息推送
                MeinformationRequest meinformationRequest = new MeinformationRequest();
                meinformationRequest.setMemberId(userId);
                meinformationRequest.setType(5);
                meinformationRequest.setTitle("您购买的" + orderGoods.getGoodsName() + "售后退款申请提交成功,请留意商家审核动态");
                meinformationRequest.setCategory(1);
                memberInformationApi.insertMemberInformation(meinformationRequest);
            }
            Integer success = this.modelService.orderAfterSaleApplyAdd(model);

            //如果是虚拟组合商品
            RestResult<ProductAfterInfoByIdResponse> responseRestResult = productListApi.queryProductInfoById(req.getGoodsId());
            if (responseRestResult.getData() != null && responseRestResult.getData().getType() != null && responseRestResult.getData().getType() == 3) {
                RestResult<List<ProductAfterInfoByIdResponse>> listRestResult = productListApi.queryProductInfoByParentId(responseRestResult.getData().getProductId());
                if (CollectionUtils.isNotEmpty(listRestResult.getData())) {
                    listRestResult.getData().forEach(item -> {
                        model.setGoodsId(item.getProductId());
                        model.setGoodsImgUrl(item.getPictureUrl());
                        model.setGoodsName(item.getChineseName());
                        model.setGoodsPrice(item.getMarketPrice());
                        this.modelService.orderAfterSaleApplyAdd(model);
                    });
                }
            }

            if (OrderAfterSalesConstant.ADD_SUCCESS.equals(success)) {
                OrderAfterSaleFlowRecordModel flowRecord = new OrderAfterSaleFlowRecordModel();
                flowRecord.setMemberId(model.getMemberId());
                flowRecord.setAfterSaleNo(model.getAfterSaleNo());
                flowRecord.setDeleteFlag(0);
                flowRecord.setGoodsId(model.getGoodsId());
                flowRecord.setGoodsNum(model.getGoodsNum());
                flowRecord.setOperateType(AfterSaleOperateTypeEnum.APP_REFUND.getCode());
                flowRecord.setOperateDetail(AfterSaleOperateTypeEnum.APP_REFUND.getMessage());
                flowRecord.setCreateName(username);
                flowRecord.setCreateTime(new Date());
                flowRecord.setCreator(userId);
                flowRecord.setUpdateName(username);
                flowRecord.setUpdateTime(new Date());
                flowRecord.setUpdater(userId);
                orderAfterSaleFlowRecordService.orderAfterSaleFlowRecordAdd(flowRecord);

                //如果是虚拟组合
                if (null != responseRestResult.getData() && null != responseRestResult.getData().getType() && responseRestResult.getData().getType() == 3) {
                    RestResult<List<ProductAfterInfoByIdResponse>> listRestResult = productListApi.queryProductInfoByParentId(responseRestResult.getData().getProductId());
                    if (CollectionUtils.isNotEmpty(listRestResult.getData())) {
                        listRestResult.getData().forEach(item -> {
                            flowRecord.setGoodsId(item.getProductId());
                            orderAfterSaleFlowRecordService.orderAfterSaleFlowRecordAdd(flowRecord);
                        });
                    }
                }

                //插入一条物流信息 如果有退货
                if (req.getAfterSaleType() == 4 || req.getAfterSaleType() == 3) {
                    OrderBaleDelivery orderBaleDelivery = new OrderBaleDelivery();
                    orderBaleDelivery.setExpressNo(req.getRestLogisticsNo());
                    List<OrderBaleDelivery> orderBaleDeliveryList = orderBaleDeliveryService.query(orderBaleDelivery);
                    if (CollectionUtils.isEmpty(orderBaleDeliveryList)) {
                        orderBaleDelivery.setOrderNo(req.getOrderNo());
                        orderBaleDelivery.setDeliveryCompanyId(Long.valueOf(req.getRestLogisticsCompany()));
                        //物流备注暂时写死
                        orderBaleDelivery.setRemark("【北京市】 快件已在 【北京太阳宫】 签收, 签收人: 前台, 如有疑问请电联:13370150897 / 010-67443169, 您的快递已经妥投。风里来雨里去, 只为客官您满意。上有老下有小, 赏个好评好不好？【请在评价快递员处帮忙点亮五颗星星哦~】");
                        orderBaleDeliveryService.insert(orderBaleDelivery);
                    }
                }
                return RestResult.success(Boolean.TRUE);
            } else {
                return RestResult.error("1101", "售后申请未成功");
            }
        } catch (Exception e) {
            String errorInfo = String.format("售后申请异常,订单编号:%s ,用户id:%s", req.getOrderNo(), userId);
            logger.error(errorInfo, e);
            return RestResult.error(OrderEnum.EX_AFTER_SALE_APPLY.getCode(), errorInfo);
        }
    }

    @ApiOperation(value = "售后-售后详情")
    @RequestMapping(value = "/query", method = {RequestMethod.POST})
    @ResponseBody
    public RestResult<OrderAfterSaleApplyQueryResponse> orderAfterSaleApplyQuery(@RequestBody OrderAfterSaleApplyQueryRequest req) {
        logger.info("------进入售后详情-----{}", req);
        String userId = getUserId(req.getToken());
        if (StringUtils.isEmpty(userId)) {
            return RestResult.error("4000", "非法请求");
        }

        OrderAfterSaleApplyQueryResponse response = new OrderAfterSaleApplyQueryResponse();
        try {
            Map param = new HashMap(5);
            // afterSaleId
            param.put("afterSaleId", req.getAfterSaleId());
            param.put("afterSaleNo", req.getAfterSaleNo());
            param.put("memberId", userId);
            OrderAfterSaleApplyModel model = this.modelService.orderAfterSaleApplyQuery(param);
            if (model == null) {
                logger.info("------售后详情,该用户无此售后详情,用户id:{},售后编号为:{}-----", userId, req.getAfterSaleNo());
                return RestResult.error(OrderEnum.ERROR_NO_AFTER_SALE_INFO.getCode(),
                        OrderEnum.ERROR_NO_AFTER_SALE_INFO.getMessage());
            }
            BeanUtils.copyProperties(model, response);

            // 获取订单信息
            RestResult<OrderInfo> orderInfoRR = orderService.info(model.getOrderNo());
            if (orderInfoRR != null && OrderEnum.SUCCESS.getCode().equals(orderInfoRR.getCode())) {
                OrderInfo orderInfo = orderInfoRR.getData();
                response.setOrderStatus(orderInfo.getOrderStatus());
            } else {
                logger.info("------无订单信息,售后编号为:{},用户id 为:{}--", req.getAfterSaleNo(), userId);
                return RestResult.error(OrderEnum.NO_ORDER_INFO.getCode(), OrderEnum.NO_ORDER_INFO.getMessage());
            }

        } catch (Exception e) {
            String errorInfo = String.format("售后详情异常,售后编号:%s ,用户id:%s", req.getAfterSaleNo(), userId);
            logger.error(errorInfo, e);
            return RestResult.error(OrderEnum.EX_AFTER_SALE_INFO.getCode(), OrderEnum.EX_AFTER_SALE_INFO.getMessage());
        }

        return RestResult.success(response);
    }

    @ApiOperation(value = "售后-售后列表")
    @RequestMapping(value = "/queryPageList", method = {RequestMethod.POST})
    @ResponseBody
    public RestResult<PageResult<OrderAfterSaleApplyModel>> orderAfterSaleApplyQueryPageList(@RequestBody OrderAfterSaleApplyQueryPageListRequest req) {
        logger.info("-------进入售后列表------{}", req);

        String userId = getUserId(req.getToken());
        if (StringUtils.isEmpty(userId)) {
            return RestResult.error("4000", "非法请求");
        }

        PageResult<OrderAfterSaleApplyModel> orderAfterSaleApplyModelPageResult = null;
        try {
            Page pageQuery = new Page();
            pageQuery.setStart(req.getStart());
            pageQuery.setLimit(req.getLimit());

            OrderAfterSaleApplyModel queryCondition = new OrderAfterSaleApplyModel();
            queryCondition.setMemberId(Long.valueOf(userId));
            queryCondition.setGoodsName(req.getGoodsName());
            queryCondition.setStatus(req.getStatus());
            orderAfterSaleApplyModelPageResult = modelService.orderAfterSaleApplyQueryPageList(queryCondition, pageQuery);
        } catch (Exception e) {
            String errorInfo = String.format("售后详情异常,用户id:%s", userId);
            logger.error(errorInfo, e);
            return RestResult.error(OrderEnum.EX_AFTER_SALE_INFO.getCode(), OrderEnum.EX_AFTER_SALE_INFO.getMessage());
        }
        return RestResult.success(orderAfterSaleApplyModelPageResult);
    }

    @ApiOperation(value = "售后-取消售后")
    @RequestMapping(value = "/cancel", method = {RequestMethod.POST})
    @ResponseBody
    public RestResult<Boolean> orderAfterSaleCancel(@RequestBody OrderAfterSaleApplyCancelRequest req) {
        logger.info("-------进入取消售后------{}", req);
        // 获取用户信息
        String userId = getUserId(req.getToken());
        if (StringUtils.isEmpty(userId)) {
            return RestResult.error("4000", "非法请求");
        }

        try {
            // 查询是否是本人的售后
            Map param = new HashMap(5);
            param.put("afterSaleNo", req.getAfterSaleNo());
            param.put("memberId", userId);
            OrderAfterSaleApplyModel orderAfterSaleApplyModel = modelService.orderAfterSaleApplyQuery(param);
            if (null != orderAfterSaleApplyModel) {
                OrderAfterSaleApplyModel modelEntity = new OrderAfterSaleApplyModel();
                modelEntity.setStatus(1020);
                modelEntity.setUpdateTime(new Date());

                OrderAfterSaleApplyModel whereCondition = new OrderAfterSaleApplyModel();
                whereCondition.setAfterSaleNo(req.getAfterSaleNo());
                whereCondition.setMemberId(Long.valueOf(userId));
                Integer updateCount = modelService.orderAfterSaleApplyEdit(modelEntity, whereCondition);
                if (OrderAfterSalesConstant.ADD_SUCCESS.equals(updateCount)) {
                    return RestResult.success(Boolean.TRUE);
                } else {
                    return RestResult.error("1102", "取消售后失败");
                }
            } else {
                logger.info("------无售后单信息,售后编号为:{},用户id 为:{}-----", req.getAfterSaleNo(), userId);
                return RestResult.error(OrderEnum.ERROR_NO_AFTER_SALE_INFO.getCode(), OrderEnum.ERROR_NO_AFTER_SALE_INFO.getMessage());
            }
        } catch (Exception e) {
            String errorInfo = String.format("取消售后异常,用户id:%s", userId);
            logger.error(errorInfo, e);
            return RestResult.error(OrderEnum.EX_AFTER_SALE_CANCEL.getCode(),
                    OrderEnum.EX_AFTER_SALE_CANCEL.getMessage());
        }
    }

    @ApiOperation(value = "售后-待售后数量")
    @RequestMapping(value = "/count", method = {RequestMethod.POST})
    @ResponseBody
    public RestResult<Integer> orderAfterSaleCount(@RequestBody OrderAfterSaleCountRequest req) {
        logger.info("-------进入待售后数量------{}", req);
        // 获取用户信息
        String userId = getUserId(req.getToken());
        if (StringUtils.isEmpty(userId)) {
            return RestResult.error("4000", "非法请求");
        }

        try {
            return RestResult.success(modelService.orderAfterSaleApplyQueryStatusListCount(Long.valueOf(userId)));
        } catch (Exception e) {
            logger.error(String.format("待售后数量异常,用户id:%s", userId), e);
            return RestResult.error(OrderEnum.EX_STAY_AFTER_SALE_COUNT.getCode(), OrderEnum.EX_STAY_AFTER_SALE_COUNT.getMessage());
        }
    }

    @ApiOperation(value = "获取配送公司信息")
    @ResponseBody
    @PostMapping(value = "/queryLogisticsCompanyList")
    public RestResult queryList() {
        OrderLogisticsCompany orderLogisticsCompany = new OrderLogisticsCompany();
        List<OrderLogisticsCompany> list = orderLogisticsCompanyService.query(orderLogisticsCompany);
        List<OrderLogisticsCompanyRestResponse> list1 = new ArrayList<>();
        list.forEach(item -> {
            list1.add(BeanUtil.copy(item, OrderLogisticsCompanyRestResponse.class));
        });
        return RestResult.success(list1);
    }

    /**
     * description: 校验是否申请过售后
     *
     * @author: jackHe
     * @time: 2020/8/28 13:51
     */
    private void checkOrderAfterApply() {

    }

    /**
     * description: 获取用户ID
     *
     * @author: jackHe
     * @time: 2020/8/28 11:50
     */
    private String getUserId(String token) {
        // 获取用户id
        String userStr = redisClientTemplate.get("H5_LOGIN_TOKEN_" + token);
        if (StringUtils.isEmpty(userStr)) {
            return "";
        }
        HashMap userMap = JSONArray.parseObject(userStr, HashMap.class);
        return userMap.get("id").toString();
    }

}
